<?php

namespace hamster\tools\com;

use MongoDB\BSON\ObjectId;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Manager;

// mongo日志类
class MongoLog
{
	public static $mongo_object = null;
	public static $mongo_config = [
		'hostname'  => '127.0.0.1',
		'username'  =>'',
		'password'  => '',
		'hostport'  => 27017,
		'database'  => 0,
		'db_name'   => 'hamster',
	];


	// $config ['hostname', 'password', 'username', 'hostport', 'database', 'db_name', '']
	public function __construct($config)
	{
		$host         = 'mongodb://' . ($config['username'] ? "{$config['username']}" : '') . ($config['password'] ? ":" . urlencode($config['password']) . "@" : '') . $config['hostname'] . ($config['hostport'] ? ":{$config['hostport']}" : '') . '/' . ($config['database'] ? "{$config['database']}" : '');
		$this->config = $config;
		$this->db     = new Manager($host);
	}

	public static function getObject($config=[])
	{
		if (self::$mongo_object) {
			return self::$mongo_object;
		}

		if (empty($config)) {
			$config = self::$mongo_config;
		}

		return new self($config);
	}

	/**
	 * 记录日志
	 * @param string $key 关键字
	 * @param string $type 时间拆分类型
	 * @param array $data 日志数据
	 * @return bool|ObjectId
	 */
	public function addLog($key, $type='day', $data=[])
	{
		switch ($type) {
			default:
			case 'day':
				$collection = $key . '_' . date('Ymd');
				break;
			case 'month':
				$collection = $key . '_' . date('Ym');
				break;
			case 'year':
				$collection = $key . '_' . date('Y');
				break;
			case 'week':
				$collection = $key . '_' . date('oW');
				break;
		}

		return $this->insert($collection, $data);
	}

	/**
	 * 插入数据
	 * @param string $collection 集合名称
	 * @param array $data 插入数据
	 * @return bool|ObjectID
	 */
	public function insert($collection, $data)
	{
		$bulk = new BulkWrite();

		$bulk->insert($data);
		$result = $this->db->executeBulkWrite("{$this->config['db_name']}.{$collection}", $bulk);

		// 成功的话，返回一个MongoDB\Driver\WriteResult实例。
		if (get_class($result) == 'MongoDB\Driver\WriteResult') {
			if (!empty($id)) {
				return $id;
			}
			return true;
		} else {
			return false;
		}
	}
}